package org.xm.sk.controller.dbase;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.data.domain.Page;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.xm.sk.common.Arith;
import org.xm.sk.exception.DataNotFoundException;
import org.xm.sk.exception.RequestParamterException;
import org.xm.sk.service.data.BaseService;
import org.xm.sk.vo.Base;
import org.xm.sk.vo.ob.Ids;
import org.xm.sk.vo.ob.MapList;
import org.xm.sk.vo.ob.PageConf;
import org.xm.sk.vo.ob.ResultMsg;
import org.xm.sk.vo.tb.Hairdresser;
import org.xm.sk.vo.tb.Item;
import org.xm.sk.vo.tb.Price;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import springfox.documentation.annotations.ApiIgnore;

@SuppressWarnings("unchecked")
@Api(tags = { "price" })
@RestController
@RequestMapping(value = "/prices")
public class PriceController {

    @Autowired
    private MessageSource messages;
    @Autowired
    private BaseService<Price> priceService;
    @Autowired
    private BaseService<Item> itemService;
    @Autowired
    private BaseService<Hairdresser> hairdresserService;

    @ApiOperation(value = "创建价格", notes = "根据price对象创建价格，使用此接口需要ADMIN权限")
    @ApiImplicitParam(name = "price", value = "价格详细实体price", required = true, dataType = "Price")
    @PreAuthorize("hasRole('ADMIN')")
    @RequestMapping(value = "", method = RequestMethod.POST)
    public ResultMsg add(@RequestBody Price price) throws RequestParamterException {
        if (null != price.getBrokerage() && 1 < price.getBrokerage()) {
            throw new RequestParamterException("佣金比例不能大于1");
        }
        Price u = null;
        if (null == price.getId() || 1 > price.getId()) {
            u = new Price();
        } else {
            u = (Price) priceService.findById(price.getId());
            if (!Base.isValid(u))
                u = new Price();
        }
        u.setHairdresser(null);
        if (null != price.getHairdresserId()
                && 0 < price.getHairdresserId()) {
            Hairdresser hairdresser = (Hairdresser) hairdresserService
                    .findById(price.getHairdresserId());
            if (Base.isValid(hairdresser))
                u.setHairdresser(hairdresser);
        }
        u.setItem(null);
        if (null != price.getItemId() && 0 < price.getItemId()) {
            Item item = (Item) itemService.findById(price.getItemId());
            if (Base.isValid(item)) {
                u.setItem(item);
                u.setName(item.getName());
            }
        }
        u.setPrice(price.getPrice());
        u.setBrokerage(price.getBrokerage());
        if (null == u.getId())
            priceService.add(u);
        else
            priceService.update(u);
        return new ResultMsg("200",
                messages.getMessage("success", null, "SUCCESS", null),
                new Date());
    }

    @ApiIgnore()
    @ApiOperation(value = "删除价格", notes = "根据URI的id来指定删除对象")
    @ApiImplicitParam(name = "id", value = "价格ID", required = true, paramType = "path", dataType = "int")
    @RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
    public ResultMsg delete(@PathVariable Integer id) {
        priceService.delete(id);
        return new ResultMsg("200",
                messages.getMessage("success", null, "SUCCESS", null),
                new Date());
    }

    @ApiOperation(value = "删除价格", notes = "根据POST的id列表来指定删除对象，可批量")
    @ApiImplicitParam(name = "ids", value = "价格ID集", required = true, dataType = "Ids")
    @RequestMapping(value = "/delete", method = RequestMethod.DELETE)
    public ResultMsg Batchdelete(@RequestBody Ids ids) {
        priceService.delete(ids.getIds());
        return new ResultMsg("200",
                messages.getMessage("success", null, "SUCCESS", null),
                new Date());
    }

    @ApiOperation(value = "更新价格详细信息", notes = "根据URI的id来指定更新对象，并根据传过来的price信息来更新价格详细信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "价格ID", required = true, paramType = "path", dataType = "int"),
            @ApiImplicitParam(name = "price", value = "待更新的价格详细实体price", required = true, dataType = "Price") })
    @RequestMapping(value = "/{id}", method = RequestMethod.PUT)
    public ResultMsg update(@PathVariable Integer id, @RequestBody Price price)
            throws DataNotFoundException {
        Price u = (Price) priceService.findById(id);
        if (null == u) {
            throw new DataNotFoundException(Price.class.getName());
        }
        price.setId(id);
        priceService.update(price);
        return new ResultMsg("200",
                messages.getMessage("success", null, "SUCCESS", null),
                new Date());
    }

    @ApiOperation(value = "获取价格详细信息", notes = "根据URI的id来获取价格详细信息")
    @ApiImplicitParam(name = "id", value = "价格ID", required = true, paramType = "path", dataType = "int")
    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    public Price load(@PathVariable Integer id) throws DataNotFoundException {
        Price u = (Price) priceService.findById(id);
        if (null == u) {
            throw new DataNotFoundException(Price.class.getName());
        }
        return u;
    }

    @ApiOperation(value = "获取价格列表", notes = "根据提交的分页信息列出所以价格信息")
    @ApiImplicitParam(name = "pageConf", value = "分页信息实体", required = true, dataType = "PageConf")
    @RequestMapping(value = { "/list" }, method = RequestMethod.POST)
    public MapList<Price> list(@RequestBody PageConf pageConf) {
        List<Price> u = null;
        Long allCount = null;
        Object o = priceService.findAllByPage(pageConf);
        if (o instanceof Page) {
            allCount = ((Page<Price>) o).getTotalElements();
            u = ((Page<Price>) o).getContent();
        } else {
            allCount = (long) ((List<Price>) o).size();
            u = (List<Price>) o;
        }
        for (Price c : u) {
            if (null != c.getItem()) {
                c.setItemId(c.getItem().getId());
                c.setItemName(c.getItem().getName());
            }
            if (null != c.getHairdresser()) {
                c.setHairdresserId(c.getHairdresser().getId());
                c.setHairdresserName(c.getHairdresser().getName());
            }
        }
        return new MapList<Price>(allCount, u);
    }

    // --------------------- 业务具体接口 ---------------------

    @ApiOperation(value = "获取指定发型师项目价格列表", notes = "根据提交的分页信息列出所有属于指定发型师的项目价格信息")
    @ApiImplicitParam(name = "pageConf", value = "分页信息实体", required = true, dataType = "PageConf")
    @RequestMapping(value = {
            "/list/{hairdresserId}" }, method = RequestMethod.POST)
    public MapList<Price> list4Hairdresser(@RequestBody PageConf pageConf,
            @PathVariable Integer hairdresserId) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("hairdressId", hairdresserId);
        List<Price> l = null;
        Long allCount = 0L;
        if (-1 < pageConf.getPage() && 0 < pageConf.getSize()) {
            Page<Price> u = (Page<Price>) priceService.findAllByPage(pageConf,
                    map);
            l = u.getContent();
            allCount = u.getTotalElements();
        } else {
            l = (List<Price>) priceService.findAllByPage(pageConf, map);
            allCount = (long) l.size();
        }
        for (Price p : l) {
            p.setItemId(p.getItem().getId());
        }
        return new MapList<Price>(allCount, l);
    }

    @ApiOperation(value = "获取指定发型师和项目求总价格", notes = "根据提交的发型师ID和项目ID集合求算总价格")
    @ApiImplicitParam(name = "ids", value = "项目ID集", required = true, dataType = "Ids")
    @RequestMapping(value = {
            "/sumprice/{hairdresserId}" }, method = RequestMethod.POST)
    public Double[] list4Hairdresser(@RequestBody Ids ids,
            @PathVariable Integer hairdresserId)
            throws RequestParamterException {
        Double price = 0.0;
        Double brokerage = 0.0;
        if (null == hairdresserId || 1 > hairdresserId || null == ids || ids.getIds().isEmpty())
            return new Double[] { price, brokerage };
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("itemIds", new ArrayList<Integer>(ids.getIds()));
        map.put("hairdressId", hairdresserId);
        List<Price> priceList = (List<Price>) priceService
                .findAllByPage(new PageConf(-1, 0), map);
        if (priceList.isEmpty()) {
            return new Double[] { price, brokerage };
        }
        for (Price pr : priceList) {
            price = Arith.add(price, pr.getPrice());
            brokerage = Arith.add(brokerage, pr.getBrokerage());
        }
        return new Double[] { price, brokerage };
    }

}
